<?php
require_once('rss_fetch.inc');
require('connect.inc.php');

function encodeText($text) {
	$str = htmlspecialchars($text, ENT_QUOTES);
	//$str = eregi_replace(chr(10), "<br />", $str);
	return trim($str);
}

/*
 * Parsing rss or atom remote file identified by $link
 * Used in function addExternalChannel($username, $link)
 * @return The channel information
 */
function parsing_channel($link) {

	// parsing the rss
	$rss = @fetch_rss($link);
	// get channel's information
	$channel = $rss->channel;
	
	if(empty($channel)) {
	
		return null;
	
	}
	
	/*
	 * do nothing for 'language' and 'docs'
	 */
	$channel['language'] = empty($channel['language']) ? '' : $channel['language'];
	$channel['docs'] = $link;
	
	/*
	 * check for 'title'
	 */
	if(!empty($channel['subtitle'])) {
	
		$channel['title'] = encodeText($channel['title']) . ' - ' . encodeText($channel['subtitle']);
	
	} else if(!empty($channel['title'])) {
	
		$channel['title'] = encodeText($channel['title']);
	
	} else {
	
		$channel['title'] = '(Title unknown)';
	
	}
	
	/*
	 * check for 'pubDate' and 'lastbuilddate'
	 */
	if(!empty($channel['pubDate']) && !empty($channel['lastbuilddate'])) {
	
		$channel['pubDate'] = date("Y-m-d H:i:s", strtotime($channel['pubDate']));
		$channel['lastbuilddate'] = date("Y-m-d H:i:s", strtotime($channel['lastbuilddate']));
	
	} else if(empty($channel['pubDate']) && !empty($channel['lastbuilddate'])) {
	
		$channel['pubDate'] = date("Y-m-d H:i:s", strtotime($channel['lastbuilddate']));
		$channel['lastbuilddate'] = date("Y-m-d H:i:s", strtotime($channel['lastbuilddate']));
	
	} else if(!empty($channel['pubDate']) && empty($channel['lastbuilddate'])) {
	
		$channel['pubDate'] = date("Y-m-d H:i:s", strtotime($channel['pubDate']));
		$channel['lastbuilddate'] = date("Y-m-d H:i:s", strtotime($channel['pubDate']));
		
	} else if(empty($channel['pubDate']) && !empty($channel['updated'])) {
	
		$channel['pubDate'] = date("Y-m-d H:i:s", strtotime($channel['updated']));
		$channel['lastbuilddate'] = date("Y-m-d H:i:s", strtotime($channel['updated']));
	
	} else {
	
		$channel['pubDate'] = date("Y-m-d H:i:s");
		$channel['lastbuilddate'] = date("Y-m-d H:i:s");
	
	}
	
	/*
	 * check for 'description'
	 */
	if(!empty($channel['description'])) { // valid RSS
	
		// do nothing
		$channel['description'] = encodeText($channel['description']);
		//$item['description'] = $item['description'];
	
	} else if(empty($channel['description']) && !empty($channel['summary'])) { // valid Atom
	
		$channel['description'] = encodeText($channel['summary']);
		//$item['description'] = $item['summary'];
	
	} else { // invalid both RSS and atom
	
		$channel['description'] = '';
	
	}
	
	return $channel;
}

function parsing_items($link) {
	// parsing the rss
	$rss = @fetch_rss($link);
	// get channel's information
	$items = $rss->items;
	
	if(empty($items)) {
	
		return null;
	
	}
	
	foreach($items as $item) {
	
		// do nothing for 'title'
		$item['title'] = encodeText($item['title']);
	
		/*
		 * check for 'pubdate'
		 */
		
		if(!empty($item['pubdate'])) { // valid RSS
		
			if(is_future_time($item['pubdate'])) {
			
				$item['real_pubdate'] = date("Y-m-d H:i:s", strtotime($item['pubdate']));
				$item['pubdate'] = date("Y-m-d H:i:s");
			
			} else {
				
				// convert to local time
				$item['pubdate'] = date("Y-m-d H:i:s", strtotime($item['pubdate']));
				$item['real_pubdate'] = $item['pubdate'];
				
			}
			
		} else if(empty($item['pubdate']) && !empty($item['published'])) { // valid Atom
			
			if(is_future_time($item['pubdate'])) {
			
				$item['real_pubdate'] = date("Y-m-d H:i:s", strtotime($item['published']));
				$item['pubdate'] = date("Y-m-d H:i:s");
			
			} else {
			
				// convert to local time
				$item['pubdate'] = date("Y-m-d H:i:s", strtotime($item['published']));
				$item['real_pubdate'] = $item['pubdate'];
			
			}
		
		} else { // invalid both RSS and atom
		
			// using time inserting instead
			$item['real_pubdate'] = empty($item['pubdate']) ? $item['published'] : $item['pubdate'];
			$item['pubdate'] = date("Y-m-d H:i:s");
		
		}
		
		/*
		 * check for 'author'
		 */
		
		$item['author'] = trim($item['author']);
		
		if(!empty($item['author'])) { // valid RSS
		
			// do nothing
			$item['author'] = $item['author'];
		
		} else if(empty($item['author']) && !empty($item['author_name'])) { // valid Atom
		
			$item['author'] = $item['author_name'];
		
		} else if(!empty($item['dc']['creator'])) {
		
			$item['author'] = $item['dc']['creator'];
		
		} else { // invalid both RSS and atom
		
			$item['author'] = '(author unknown)';
		
		}
		
		/*
		 * check for 'description'
		 */
		if(!empty($item['description'])) { // valid RSS
		
			// do nothing
			$item['description'] = encodeText($item['description']);
			//$item['description'] = $item['description'];
		
		} else if(empty($item['description']) && !empty($item['summary'])) { // valid Atom
		
			$item['description'] = encodeText($item['summary']);
			//$item['description'] = $item['summary'];
		
		} else { // invalid both RSS and atom
		
			$item['description'] = '';
		
		}
		
		$item['description'] .= encodeText('<br /><a href="' . $item['link'] . '"  target="_blank">read more...</a>');
		
		$new_items[] = $item;
		
	}
	
	return $new_items;
}

function is_channel_duplicate($channel) {
	
	global $db;
	
	$sql = "SELECT id AS channel_id FROM channel WHERE title = '" . $channel['title'] . "' AND link = '" . $channel['link'] . "'";
	$query = $db->sql_query($sql);
	$row = $db->sql_fetchrow($query);
	return !empty($row['channel_id']);
}

/*
 * Add new external channel data into 'channel' table in database
 * Used in function addExternalChannel($username, $link)
 * @return true if inserting succeeds
 */
function insert_channel_info($channel, $title = '') {

	if(is_channel_duplicate($channel)) {	
		return false;		
	}
	
	if(empty($channel)) {	
		return true;
	}

	global $db;
	
	$title = empty($title) ? $channel['title'] : $title;
	
	$sql = "INSERT INTO channel (title, link, description, pubdate, language, 
				lastbuilddate, docs, rank
			) VALUES ( 
				'" . $title . "', 
				'" . $channel['link'] . "', 
				'" . $channel['description'] . "', 
				'" . $channel['pubDate'] . "', 
				'" . $channel['language'] . "', 
				'" . $channel['lastbuilddate'] . "', 
				'" . $channel['docs'] . "', 
				'1');";
	
	return $db->sql_query($sql);
	
}

function insert_items($items, $channel_id) {

	global $db;
	$flag = true;
	
	if(empty($items)) {
		return true;
	}
	
	foreach($items as $item) {
		
		//$item['description'] .= " <a href='" . $item['link'] . "'>read more...</a>";
		
		$sql = "INSERT INTO item(channelid, title, link, description, pubdate, author, isPublish, real_pubDate)
				VALUES (
				'" . $channel_id . "', 
				'" . $item['title'] . "', 
				'" . $item['link'] . "', 
				'" . $item['description'] . "', 
				'" . $item['pubdate'] . "', 
				'" . $item['author'] . "', 
				'1', 
				'" . $item['real_pubdate'] . "')";
		$flag &= $db->sql_query($sql);
	}
	
	return $flag;
}

/*
 * This function is for finding the channel id of the channel link identified.
 * Used in function addExternalChannel($username, $link)
 * @param $link The link of the channel to be found.
 * @return The channel id
 */

function get_channelid($channel_link) {

	global $db;
	
	$sql = "SELECT id AS channelid FROM channel WHERE docs = '" . $channel_link . "'";
	$query = $db->sql_query($sql);
	$line = $db->sql_fetchrow($query);
	return $line['channelid'];
}

/*
 * This function is for check whether the item to be inserted is duplicated.
 */
function is_duplicate_item($channel_id, $item_title, $item_link) {
	
	global $db;
	
	$sql = "SELECT item.id AS item_id
			FROM externalfeed INNER JOIN channel 
			ON externalfeed.link = channel.docs 
			INNER JOIN item ON channel.id = item.channelid 
			WHERE item.channelid = '" . $channel_id . "' 
			AND item.title = '" . $item_title . "' 
			AND item.link = '" . $item_link . "'";
	$query = $db->sql_query($sql);
	$first_row = $db->sql_fetchrow($query);

	return !empty($first_row);
}

/*
 * This function is for finding the channel which is least recently updated.
 * @return The least recently updated channel.
 */
function get_least_recently_updated_channel() {

	global $db;
	
	$sql = "SELECT channel.id AS channel_id, externalfeed.link AS ext_link 
			FROM externalfeed INNER JOIN channel ON externalfeed.link = channel.docs 
			ORDER BY externalfeed.lastupdate ASC";
	$query = $db->sql_query($sql);
	$min_row = $db->sql_fetchrow($query);
	
	return $min_row;
}

function is_future_time($str_time) {
	return strtotime($str_time) > time();
}
?>